#include <stdio.h>
#include <pthread.h>

int g_nsrc = 0;
int g_y = 0;
pthread_cond_t th_cond = PTHREAD_COND_INITIALIZER;

void* produce(void *param)
{
	pthread_mutex_t *mutex = (pthread_mutex_t *)param;
	while(1)
	{
		pthread_mutex_lock(mutex);
		printf("th1-----=%d\n", ++g_nsrc);
		if(g_nsrc == 2)
		{
			pthread_cond_broadcast(&th_cond);
		}
		pthread_mutex_unlock(mutex);

		usleep(1000000);
	}

	return ;
};

void* consume(void *param)
{
	pthread_mutex_t *mutex = (pthread_mutex_t *)param;

	while(1)
	{
		pthread_mutex_lock(mutex);
		if(g_nsrc < 2)
		{
			printf("%ld will enter waiting!\n", (long)pthread_self());
			pthread_cond_wait(&th_cond, mutex);
		}		
		
		printf("%ld----- =%d\n", (long)pthread_self(), --g_nsrc);
		pthread_mutex_unlock(mutex);

		usleep(1000);
	}

	return ;
};


int main()
{
	pthread_t thrd1, thrd2,thrd3;

	pthread_mutex_t th_mutex = PTHREAD_MUTEX_INITIALIZER;
	
	int nrst = pthread_create(&thrd1, NULL, consume, (void *)&th_mutex);
	if( nrst != 0 )
	{
		printf("create thread failed! error code is %d\n", nrst);
	}
	
	nrst = pthread_create(&thrd2, NULL, produce, (void *)&th_mutex);	
	if( nrst != 0 )
	{
		printf("create thread failed! error code is %d\n", nrst);
	}

	nrst = pthread_create(&thrd3, NULL, consume, (void *)&th_mutex);	
	if( nrst != 0 )
	{
		printf("create thread failed! error code is %d\n", nrst);
	}

	pthread_join(thrd1, NULL);
	pthread_join(thrd2, NULL);
	pthread_join(thrd3, NULL);	

	return 0;
}
